import { createRouter, createWebHistory } from 'vue-router'
import { getUserInfo } from '@/api/user'
import UserLogin from '@/components/UserLogin'
import AppMenu from '@/components/AppMenu'
import SystemUser from '@/components/system/user'
import SystemDept from '@/components/system/dept'
import SystemPost from '@/components/system/post'

const routes = [
    {
        path: '/',
        redirect: '/UserLogin'  // 根路径重定向到登录页
    },
    {
        path: '/UserLogin',
        name: 'Login',
        component: UserLogin
    },
    {
        path: '/AppMenu',
        name: 'AppMenu',
        component: AppMenu,
        redirect: '/system/user',  // 可选：重定向到用户管理页面
        children: [
            {
                path: '/system/user',
                name: 'SystemUser',
                component: SystemUser,
                meta: { 
                    title: '用户管理',
                    icon: 'user'
                }
            },
            {
                path: '/system/dept',
                name: 'SystemDept',
                component: SystemDept,
                meta: { title: '部门管理', icon: 'tree' }
            },
            {
                path: '/system/post',
                name: 'SystemPost',
                component: SystemPost,
                meta: { title: '岗位管理', icon: 'post' }
            },
            // 这里可以继续添加其他系统管理的子路由
            // {
            //     path: '/system/role',
            //     name: 'SystemRole',
            //     component: () => import('@/components/system/role.vue'),
            //     meta: { title: '角色管理' }
            // },
            // {
            //     path: '/system/menu',
            //     name: 'SystemMenu',
            //     component: () => import('@/components/system/menu.vue'),
            //     meta: { title: '菜单管理' }
            // }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 添加全局路由守卫
router.beforeEach(async (to, from, next) => {
    // 白名单路径，不需要验证登录状态
    const whiteList = ['/UserLogin']
    
    if (whiteList.includes(to.path)) {
        next()
        return
    }

    try {
        // 调用接口检查登录状态
        await getUserInfo()
        next()
    } catch (error) {
        next('/UserLogin')
    }
})

export default router

